import {Injectable} from '@angular/core';

/*
 Generated class for the LocalstorageProvider provider.

 See https://angular.io/guide/dependency-injection for more info on providers
 and Angular DI.
 */
@Injectable()
export class LocalstorageProvider {

  constructor() {
    console.log('欢迎使用localstorage的服务');
  }

  /**
   * 设置localstorage
   * @param {[type]} key   [键名]
   * @param {[type]} value [键值]
   * @param {[type]} Days  [保存的时间（天）]
   */
  set(key: string, value: any, Days: number = 3) {
    // 设置过期原则
    if (!value) {
      localStorage.removeItem(key)
    } else {
      var exp = new Date();
      localStorage.setItem(key, JSON.stringify({
        value,
        expires: exp.getTime() + Days * 24 * 60 * 60 * 1000
      }))
    }
  };

  get(name: string) {
    let getstr = localStorage.getItem(name)
    if (getstr) {
      let o = JSON.parse(getstr)
      if (!o || o.expires < Date.now()) {
        return null
      } else {
        return o.value
      }
    } else {
      return null
    }

  };

  remove(key: string) {
    localStorage.removeItem(key)
  }

  clear() {
    localStorage.clear();
  }
}
